import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/collection_list_entity.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/service_list_entity.dart';
import '../../bean/simple_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'package:get/get.dart';

class CollectionController extends GetxController {
  EasyRefreshController easyRefreshController = EasyRefreshController(
  controlFinishRefresh: false,
  controlFinishLoad: true,
  );
  @override
  void onInit() {
    super.onInit();

    _getService();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<CollectionListData> list = [];
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.collectList,{
      "user_name":UserUtil.getUSER()?.userName.toString()
    }, (data) async {
      CollectionListEntity bannerEntity = CollectionListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _goodsCollect(CollectionListData item){
    DioManager.getInstance().post(ServiceUrl.goodsCollect,{
      "channel_name":item.channelName,
      "goods_id":item.articleId.toString(),
      "user_id":UserUtil.getUSER()?.id.toString(),
      "type":"0"
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code ==200){
        _getService();
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }
}


class CollectionPage extends GetView<CollectionController> {
  // @override
  // void initState() {
  //   super.initState();
  //   _controller = EasyRefreshController(
  //     controlFinishRefresh: true,
  //     controlFinishLoad: true,
  //   );
  // }

  late CollectionController controller;

  late BuildContext context;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<CollectionController>(() => CollectionController());
    controller = Get.find();
    context = context1;

    return GetBuilder<CollectionController>(
      builder: (_) {
        return Scaffold(
            appBar: MyAppBar(
              context: context,
              title: '我的收藏',
              hasLeading: true,
            ),
            backgroundColor: Colors.white,
            body: controller.list.isEmpty?Container(): _content());
      },
    );
  }

  Widget _content() {
    return EasyRefresh(
        header: ClassicHeader(
          dragText: 'Pull to refresh'.tr,
          armedText: 'Release ready'.tr,
          readyText: 'Refreshing...'.tr,
          processingText: 'Refreshing...'.tr,
          processedText: 'Succeeded'.tr,
          noMoreText: 'No more'.tr,
          failedText: 'Failed'.tr,
          messageText: 'Last updated at %T'.tr,
        ),
        footer: ClassicFooter(
          dragText: 'Pull to load'.tr,
          armedText: 'Release ready'.tr,
          readyText: 'Loading...'.tr,
          processingText: 'Loading...'.tr,
          processedText: 'Succeeded'.tr,
          noMoreText: 'No more'.tr,
          failedText: 'Failed'.tr,
          messageText: 'Last updated at %T'.tr,
        ),
        controller: controller.easyRefreshController,
        onRefresh: () async {},
        onLoad: () async {
          controller.easyRefreshController.finishLoad(
              IndicatorResult.noMore );
        },
        child: ListView.separated(
          itemBuilder: (context, index) {
            return _gameItems(controller.list[index]);
          },
          separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 8.h,
              color: Color(0xFFF7F8FC),
            );
          },
          itemCount: controller.list.length,
        ));
  }

  Widget _gameItems(CollectionListData item) {
    return InkWell(
        onTap: () {
          if(item.status == 0){
            ToastUtil.show('该商品已售罄');
            return;
          }
          Get.to(()=>DetailPage(),arguments: {
            "title":item.title,
            "record_id":item.channelId.toString(),
            "channel_name":item.channelName,
            "goods_id":item.guid.toString(),
          },preventDuplicates:false);
        },
        child: Container(
          margin: EdgeInsets.only(left: 16.w, right: 13.w, top: 6.h),
          child: Column(
            children: [
              Row(
                children: [
                  Container(
                      width: 120.w,
                      height: 88.h,
                      child: Stack(
                        children: [
                          ClipRRect(
                              borderRadius: BorderRadius.circular(10.r),
                              child: Image.network( item.imgUrl,fit: BoxFit.cover,width: 120.w,height: 88.h,)
                          ),
                          _officer(),
                        ],
                      )),
                  SizedBox(
                    width: 8.w,
                  ),
                  Container(
                      width: MediaQuery.of(context).size.width -
                          29.w -
                          14.w -
                          120.w,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.title,
                            style: TextStyle(
                              color: Color(0xFF333333),
                              fontSize: 14.sp,
                            ),
                            maxLines: 2,
                            textAlign: TextAlign.left,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(
                            height: 10.h,
                          ),
                          Text(
                            '区服：${item.categoryText}',
                            style: TextStyle(
                                color: Color(0xFF666666), fontSize: 13.sp),
                          ),
                          SizedBox(
                            height: 6.h,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              _second(item.isMsg),
                              Row(
                                children: [
                                  Text(
                                    '¥',
                                    style: TextStyle(
                                        color: Color(0xFFFF0000),
                                        fontSize: 12.sp),
                                  ),
                                  Text(
                                    item.sellPrice,
                                    style: TextStyle(
                                        color: Color(0xFFFF0000),
                                        fontSize: 18.sp),
                                  ),
                                ],
                              )
                            ],
                          )
                        ],
                      ))
                ],
              ),
              SizedBox(
                height: 13.h,
              ),
              _info(item),
              _btn(item)
            ],
          ),
        ));
  }

  Widget _second(ismsg) {
    return Container(
      width: 50.w,
      height: 20.h,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(width: 1.w, color: Color(0xFF007BE5))),
      child: Text(
        '可二次',
        style: TextStyle(color: Color(0xFF007BE5), fontSize: 12.sp),
      ),
    );
  }

  Widget _officer() {
    return Container(
      child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
    );
  }

  Widget _info(CollectionListData item) {
    return Container(
      color: Color(0xFFFBFBFB),
      padding: EdgeInsets.all(10.w),
      child: Column(
        children: [
          Row(
            children: [
              Flexible(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            '游戏:',
                            style: TextStyle(
                                color: Color(0xFF666666), fontSize: 13.sp),
                          ),
                          Text(
                            item.subTitle,
                            style: TextStyle(
                                color: Color(0xFFFF9100), fontSize: 15.sp),
                          ),
                        ],
                      ),
                    ],
                  )),
              Flexible(
                flex: 1,
                child: Text(
                  '上架：${Common.transferDate2(item.addTime) }',
                  style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
                ),
              ),

              // Flexible(
              //   flex: 1,
              //   child: Text(
              //     '上架：2023.05.10  10:30',
              //     style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
              //   ),
              // ),
            ],
          ),

          Row(
            children: [
              Flexible(
                  flex: 1,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            '状态:',
                            style: TextStyle(
                                color: Color(0xFF666666), fontSize: 13.sp),
                          ),

                          Text(
                            item.status==1? '在售':'已售罄',
                            style: TextStyle(
                                color: item.status==1?Color(0xFF00D841):Color(0xFF666666), fontSize: 13.sp),
                          ),
                          item.status==1?
                          Image.asset('${Constant.IMG_BASE}saling.png',width: 10.w,height: 10.w,):
                          Image.asset('${Constant.IMG_BASE}saled.png',width: 10.w,height: 10.w,)

                        ],
                      ),
                    ],
                  )),
              Flexible(
                flex: 1,
                child: Text(
                  '商品编号：${item.id}',
                  style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
                ),
              ),

              // Flexible(
              //   flex: 1,
              //   child: Text(
              //     '上架：2023.05.10  10:30',
              //     style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
              //   ),
              // ),
            ],
          ),
          SizedBox(
            height: 7.h,
          ),
          // Row(
          //   children: [
          //     Expanded(
          //       flex: 1,
          //       child: Text(
          //         '商品类型:官方',
          //         style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
          //       ),
          //     ),
          //     Expanded(
          //       flex: 1,
          //       child: Text(
          //         '营地号:asasasasa',
          //         style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
          //       ),
          //     ),
          //   ],
          // ),
          // SizedBox(
          //   height: 7.h,
          // ),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     Text(
          //       '商品编号：${item.}',
          //       style: TextStyle(color: Color(0xFF666666), fontSize: 13.sp),
          //     ),
          //   ],
          // ),
        ],
      ),
    );
  }

  Widget _btn(item) {
    return InkWell(
      onTap: (){
        controller._goodsCollect(item);
      },
      child:  Container(
          height: 36.h,
          margin: EdgeInsets.only( bottom: 10.h),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(20.r)),
              border: Border.all(color: Color(0xFF007BE5), width: 1.w)),
          child: Text(
            '取消收藏',
            style: TextStyle(fontSize: 13.sp, color: Color(0xFF007BE5)),
          ))
    );
  }
}
